package rbac.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import rbac.dao.PermissionDao;
import rbac.entity.RbacPermission;


/**
 * RBAC 权限管理 DAO 实现类.<br>
 * 该接口供开发人员开发阶段编辑权限使用, 系统发布时不应提供此接口.
 * 
 * @author Huadi
 */
@Repository("permissionDao")
public class PermissionDaoImpl extends HibernateDaoSupport implements
		PermissionDao {

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor={Exception.class})
	public void delete(RbacPermission permission) {
		// XXX: 删除关系表中的实体关系记录, 此处与实体表耦合.
		Query query = getSession().createSQLQuery(
				"DELETE FROM t_rbac_role_permission WHERE permission_id = :id");
		query.setInteger("id", permission.getId());
		query.executeUpdate();
		getHibernateTemplate().delete(permission);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor={Exception.class})
	public RbacPermission getPermission(Integer id) {
		return (RbacPermission) getHibernateTemplate().get(
				RbacPermission.class, id);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor={Exception.class})
	public void save(RbacPermission permission) {
		getHibernateTemplate().save(permission);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor={Exception.class})
	public void update(RbacPermission permission) {
		getHibernateTemplate().update(permission);
	}

	/**
	 * 此方法会与数据库交互2次, 通常不应使用此方法. 考虑到 <code>Permission</code> 相关操作只在开发中进行, 则提供此方法.
	 */
	@Override
	@Deprecated
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor={Exception.class})
	public void delete(Integer id) {
		this.delete(this.getPermission(id));
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor={Exception.class})
	public List<RbacPermission> getAllPermissions() {
		Query q = getSession().getNamedQuery("permission.getAllPermissions");
		return q.list();
	}

}
